package ua.kharkov.knure.mikhaylov.st4.web.command;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.mikhaylov.st4.db.entities.Account;
import ua.kharkov.knure.mikhaylov.st4.db.entities.Card;
import ua.kharkov.knure.mikhaylov.st4.db.management.DBManager;
import ua.kharkov.knure.mikhaylov.st4.settings.LocaleData;
import ua.kharkov.knure.mikhaylov.st4.settings.Path;

/**
 * Command - creates a card
 * 
 * @author Saint
 * 
 */
public class CreateCardCommand extends Command {

	private static final long serialVersionUID = -8297348005094960450L;
	private static final Logger log = Logger.getLogger(CreateCardCommand.class);

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		log.debug("Command starts");

		log.trace("Checking parameters");

		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("account");

		// error handler
		String errorMessage = null;
		String forward = Path.PAGE_ERROR;

		if (account == null) {
			errorMessage = LocaleData.getResourceBundle().getString(
					"servlet.error.account.notchosen");
			request.setAttribute("errorMessage", errorMessage);
			log.error("errorMessage --> " + errorMessage);
			return forward;
		}

		log.trace("Creating a new card");

		Card card = new Card();

		card.generateSecCode();
		card.setAccount(account);
		card.generateNumber();

		log.trace("Card number generated --> " + card.getNumber());
		log.trace("Card security code generated --> " + card.getSecurityCode());

		DBManager.getInstance().insertCard(card);

		log.debug("Card saved");

		request.setAttribute("message", LocaleData.getResourceBundle()
				.getString("servlet.success.card.save"));
		request.setAttribute("next", Path.COMMAND_VIEW_ACCOUNT);
		forward = Path.PAGE_SUCCESS;

		log.debug("Command finished");
		return forward;
	}

}
